package me.joshua.demo4j.bae.demo;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import com.baidu.bae.api.bcms.BaeBcms;
import com.baidu.bae.api.bcms.model.concrete.MailRequest;
import com.baidu.bae.api.factory.BaeFactory;
import com.baidu.bae.api.fetchurl.BaeFetchurl;

public class TokyoRavensServlet extends HttpServlet {

	private static final long serialVersionUID = -7329388165124974167L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {

			BaeFetchurl fetchUrl = BaeFactory.getBaeFetchurl();
			String content = fetchUrl.get("http://manhua.dmzj.com/dongjingwuya/");
			Document doc = Jsoup.parse(content);
			Element element = doc.select("span.update2").first();
			String updateDate = element.text();
			PrintWriter pw = resp.getWriter();
			pw.println(updateDate);
			element = doc.select("div.cartoon_online_border ul li:last-child a").first();
			pw.println("<br />");
			String url = "http://manhua.dmzj.com" + element.attr("href");
			pw.println(url);
			pw.println(String.format("<a href=\"%s\">%s</a>", url, "TokyoRavens"));
			
			BaeBcms bcms = BaeFactory.getBaeBcms();
			MailRequest mailRequest = new MailRequest();
			mailRequest.setQueueName("ee7689d55b8e76bebb63509dd805d37d");
			mailRequest.setMessage(String.format("<a href=\"%s\">%s</a>", url, "Tokyo Ravens"));
			mailRequest.addMailAddress("daonan.zhan@gmail.com");
			mailRequest.setFrom("daonan.zhan@gmail.com");
			mailRequest.setSubject("Tokyo Ravens");
			bcms.mail(mailRequest);
		} catch (Exception e) {
			PrintWriter pw = resp.getWriter();
			e.printStackTrace(pw);
		}
	}
}
